package net.majodali.glasshouse;

import java.util.regex.Pattern;

public class ResourceNameMatcher implements ResourceMatcher {
	Pattern pattern;
	
	public ResourceNameMatcher(String pattern) {
		this.pattern = convertAntPath(pattern);
	}

	@Override
	public boolean matches(Resource resource) {
		return pattern.matcher(resource.getFullName()).matches();
	}
	
	public static Pattern convertAntPath(String path) {
		StringBuilder pattern = new StringBuilder();
		if (!path.startsWith("/"))
			pattern.append("(.*/)?");
		for (int i = 0; i < path.length(); i++)
			if (path.charAt(i) == '*')
				if (i+1 < path.length() && path.charAt(i+1) == '*') {
					pattern.append(".*");
					i++;
				}
				else
					pattern.append("[^/]*");
			else {
				if (".$^()[]?".indexOf(path.charAt(i)) != -1)
					pattern.append("\\");
				
				pattern.append(path.charAt(i));
			}
		Pattern p = Pattern.compile(pattern.toString());
		return p;
	}
}
